#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

#include "ds18b20_temp.h"

int get_temp(float *temp)
{
	int             	fd;
	char            	buf[128];
	char 				*ptr = NULL;
	DIR 				*dirp = NULL;
	struct dirent 		*direntp = NULL;
	char				w1_path[64] = "/sys/bus/w1/devices/";
	char 				chip_sn[32];
	int					found = 0;
	int					rv = 0;

	dirp = opendir(w1_path);
	if( !dirp )
	{
		printf("Open folder %s failure: %s \n", w1_path, strerror(errno));
		return -1;
	}	       

	while( NULL != (direntp = readdir(dirp)) )
	{
		if( strstr(direntp->d_name, "28-") )
		{
			strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));
			found = 1;
		}
	}

	closedir(dirp);

	if ( !found )
	{
		printf("Can not find ds18b20 chipset !!!\n");
		rv = -2;
		goto cleanup;
	}

	strncat( w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path));
	strncat( w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));

	//PARSE_LOG_DEBUG("w1_path: %s\n", w1_path); 

	/* printf("%s/%s/w1_slave\n", w1_path, chip_sn);
	   snprintf(ds18b20_path,  sizeof(ds18b20_path), "%s/%s/w1_slave\n", w1_path, chip_sn);创个变量ds18b20_path，而不用w1_path，否则会有内存重叠从而无法实现目标
	   printf("w1_path: %s", ds18b20_path); */
	fd = open(w1_path, O_RDONLY);
	if( fd < 0)
	{
		printf("open file failure: %s\n", strerror(errno));
		return -3;
	}

	memset(buf, 0, sizeof(buf));
	if ( read(fd, buf, sizeof(buf)) < 0)
	{
		printf("Read data from fd=%d failure: %s\n", fd, strerror(errno));
		rv = -4;
		goto cleanup;
	}
	//PARSE_LOG_DEBUG("buf:\n%s\n", buf);

	ptr = strstr(buf, "t=");
	if( !ptr)//ptr=NULL   ptr=(void *)0无类型的一个指针
	{
		printf("Can not find 't=' string\n");
		rv = -5;
		goto cleanup;
	}

	ptr += 2;
	//PARSE_LOG_DEBUG("ptr: %s\n", ptr);

	*temp = atof(ptr)/1000;
	//PARSE_LOG_DEBUG("temprature:%f\n", *temp);

cleanup:
	close(fd);
	return rv;

}

